import sys
import time
import random
import zmq


def main(myself, others):
    print("Hello, I am %s" % myself)
    context = zmq.Context()
    statebe = context.socket(zmq.PUB)
    statefe = context.socket(zmq.SUB)
    statefe.setsockopt(zmq.SUBSCRIBE, b'')

    bind_address = "ipc://%s-state.ipc" % myself
    statebe.bind(bind_address)

    for other in others:
        statefe.connect("ipc://%s-state.ipc" % other)
        time.sleep(1.0)

    poller = zmq.Poller()
    poller.register(statefe, zmq.POLLIN)

    while True:
        socks = dict(poller.poll(1000))
        if socks.get(statefe) == zmq.POLLIN:
            msg = statefe.recv_multipart()
            print('%s Received: %s' % (myself, msg))
        else:
            msg = [bind_address, ('%i' % random.randrange(1, 10))]
            msg = [m.encode("utf-8") for m in msg]
            statebe.send_multipart(msg)


if __name__ == "__main__":
    if len(sys.argv) > 2:
        main(myself=sys.argv[1], others=sys.argv[2:])
    else:
        print("Usage: peering.py <myself> <peer_1> ... <peer_N>")
        sys.exit(1)
